package com.ndk.head;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageProxy;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.util.Size;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.TextView;

import com.google.common.util.concurrent.ListenableFuture;
import com.ndk.head.usb.UsbCameraActivity;
import com.ndk.head.util.PermissionUtil;
import com.ndk.head.view.DialogManager;

public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, ImageAnalysis.Analyzer {

    private FaceTracker faceTracker;
    private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
    private SurfaceView surfaceView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        init();
    }

    private void initView() {
        surfaceView = findViewById(R.id.surfaceView);
        surfaceView.getHolder().addCallback(this);
    }

    private void init() {
        if (initPermission() && faceTracker == null) {
            initCamera();
            String path = Utils.copyAsset2Dir(this, "lbpcascade_frontalface.xml");
            faceTracker = new FaceTracker(path);
            faceTracker.start();
        }
    }

    private boolean initPermission() {
        // 判断是否需要动态申请权限
        if (!PermissionUtil.checksStoragePermission(this)) {
            DialogManager.getInstance().showDialog(getString(R.string.storage_tip1), this, () ->
                    PermissionUtil.requestStoragePermission(this));
            return false;
        }
        // 判断是否需要动态申请相机权限
        if (!PermissionUtil.checksCameraPermission(this)) {
            DialogManager.getInstance().showDialog(getString(R.string.camera_tip), this, () ->
                    PermissionUtil.requestCameraPermission(this));
            return false;
        }
        // 已授权
        return true;
    }

    private void initCamera() {
        /**
         *  CameraX
         */
        cameraProviderFuture = ProcessCameraProvider.getInstance(this);
        cameraProviderFuture.addListener(() -> {
            try {
                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
                bindAnalysis(cameraProvider);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }, ContextCompat.getMainExecutor(this));
    }

    private void bindAnalysis(ProcessCameraProvider cameraProvider) {
        //STRATEGY_KEEP_ONLY_LATEST :非阻塞模式，每次获得最新帧
        //STRATEGY_BLOCK_PRODUCER : 阻塞模式，处理不及时会导致降低帧率
        //图片分析：得到摄像头图像数据
        ImageAnalysis imageAnalysis =
                new ImageAnalysis.Builder()
                        .setTargetResolution(new Size(640, 480))
                        .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
                        .build();
        imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(this), this);
        cameraProvider.unbindAll();
        //绑定生命周期
        cameraProvider.bindToLifecycle(this,
                CameraSelector.DEFAULT_BACK_CAMERA, imageAnalysis);
    }

    public void init(View view) {
        init();
        startActivity(new Intent(this, UsbCameraActivity.class));
    }

    /**
     * 预览数据
     *
     * @param holder
     */
    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
        if (faceTracker != null)
            faceTracker.setSurface(holder.getSurface());
    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
        if (faceTracker != null)
            faceTracker.setSurface(null);
    }

    /**
     * 相机数据
     *
     * @param image
     */
    @Override
    public void analyze(@NonNull ImageProxy image) {
        byte[] bytes = Utils.getDataFromImage(image);
        // 定位人脸，并且显示摄像头的图像
        faceTracker.detect(bytes, image.getWidth(), image.getHeight(), image.getImageInfo().getRotationDegrees());
        image.close();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        faceTracker.release();
    }
}